//
//  BCSafeCenterController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/15.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "BCSafeCenterController.h"
//
#import "BCSafeCenterCellModel.h"
//cell
#import "BCSafeCenterBaseCell.h"
//
#import "LocalAuthenticationManager.h"

//vcs
#import "BCMobileVerificationController.h"//手机验证
#import "BCEmailVerificationController.h"//邮箱验证
#import "BCWalletPassSetController.h"//支付密码

#import "BCLALoginPasswordController.h"//输入登录密码和设置登录

//request
#import "BCUserSafeCenterRequest.h"
#import "BCUserFingerPrintDeleteRequest.h"

@interface BCSafeCenterController () <UITableViewDataSource,UITableViewDelegate,BCSafeCenterCellDelegate>

@property (nonatomic, strong) UITableView *safeTable;

/**
 *safeSource
 */
@property (nonatomic, strong) NSMutableArray *safeSource;

#pragma mark - sourceModel
//电话
@property (nonatomic, strong) BCSafeCenterCellModel *phone;
//邮箱
@property (nonatomic, strong) BCSafeCenterCellModel *email;
//支付密码
@property (nonatomic, strong) BCSafeCenterCellModel *payPasswrod;
//指纹登录
@property (nonatomic, strong) BCSafeCenterCellModel *fingerprintLogin;





#pragma mark - 一些临时对象 后续需要操作

/**
 *fingerSwitch 指纹或面容开启关闭的switch 在成功后需要操作
 */
@property (nonatomic, weak) UISwitch *fingerSwitch;
/**
 *switchButton fingerSwitch对应的按钮 在点击后关闭手势 在完成验证后在开启手势
 */
@property (nonatomic, weak) QMUIButton *switchButton;

@end

@implementation BCSafeCenterController

- (BCSafeCenterCellModel *)phone {
    if (!_phone) {
        _phone = [BCSafeCenterCellModel phone];
    }
    return _phone;
}
- (BCSafeCenterCellModel *)email {
    if (!_email) {
        _email = [BCSafeCenterCellModel email];
    }
    return _email;
}
- (BCSafeCenterCellModel *)payPasswrod {
    if (!_payPasswrod) {
        _payPasswrod = [BCSafeCenterCellModel payPassword];
    }
    return _payPasswrod;
}
- (BCSafeCenterCellModel *)fingerprintLogin {
    if (!_fingerprintLogin) {
        _fingerprintLogin = [BCSafeCenterCellModel fingerPrintLogin];
    }
    return _fingerprintLogin;
}

- (NSMutableArray *)safeSource {
    if (!_safeSource) {
        _safeSource = [NSMutableArray array];
    }
    return _safeSource;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //
//    self.title = BCLocalizedKey(@"uc_safe_center");
    //
    [self setupSubviews];
    //request
    BCUserSafeCenterData *safeData = [BCUserManager sharedUser].safeCenterData;
    if (safeData) {
        [self handleSafeData:safeData];
    }else {
        [self requestSafeDataInit:true refresh:false];
    }
    //
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(safeCenterdataUpdateNotification:) name:UserSafeCenterUpdateNotification object:nil];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //
    [self requestSafeDataInit:false refresh:true];
}



- (void)setupSubviews {
    self.safeTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.safeTable.separatorStyle = UITableViewCellSelectionStyleNone;
    self.safeTable.dataSource = self;
    self.safeTable.delegate = self;
    [self.view addSubview:self.safeTable];
    [self.safeTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.customNaviBar.mas_bottom);
        make.left.bottom.right.mas_equalTo(self.view);
    }];
    //
    for (NSString *className in [BCSafeCenterCellModel registerCells]) {
        [self.safeTable registerClass:NSClassFromString(className) forCellReuseIdentifier:className];
    }
    //
    [self.view layoutIfNeeded];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.safeSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BCSafeCenterCellModel *cellModel = [self.safeSource objectAtIndex:indexPath.row];
    BCSafeCenterBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(cellModel.cellClass)];
    cell.cellModel = cellModel;
    cell.delegate = self;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    BCSafeCenterCellModel *cellModel = [self.safeSource objectAtIndex:indexPath.row];
    return [BCSafeCenterBaseCell defaultHeight];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BCSafeCenterCellModel *cellModel = [self.safeSource objectAtIndex:indexPath.row];
    switch (cellModel.cellType) {
        case BCSafeCenterCellTypePhone:
        {
            [self toMobilePhoneVerificationAction];
        }
            break;
        case BCSafeCenterCellTypeEmail:
        {
            [self toEmailVerificationAction];
        }
            break;
        case BCSafeCenterCellTypePayPassword:
        {
            [self toWalletPasswordSetAction];
        }
            break;
        case BCSafeCenterCellTypeFingerPrintLogin:
        {
            
        }
            break;
        default:
            break;
    }
}

#pragma mark - BCSafeCenterCellDelegate
- (void)safeCenterCell:(BCSafeCenterBaseCell *)cell fingerSwitch:(UISwitch *)cellSwitch fingerButtin:(QMUIButton *)fingerButton {
    self.fingerSwitch = cellSwitch;
    self.switchButton = fingerButton;
    /**
     switch.on NO说明要去开启 YES说明要关闭
     */
    BOOL on = cellSwitch.on;
    if (on) {//提示用户是否需要关闭
        [self showCloseFingerPrintAlert];
    }else {
        [self handleLocalAuthenticationOn:cellSwitch.on];
    }
}
- (void)showCloseFingerPrintAlert {
    NSString *title = BCLocalizedFormatString(@"Sure to close \"%@\"",self.fingerprintLogin.title);
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    WEAK_SELF
    UIAlertAction *sure = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Sure") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [wself localAuthenticationSuccessToClose];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Cancel") style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:sure];
    [alertVC addAction:cancel];
    [self.navigationController presentViewController:alertVC animated:true completion:nil];
}



#pragma mark - requestData
/**
 请求安全中心数据
 */
- (void)requestSafeDataInit:(BOOL)init refresh:(BOOL)refresh {
    if (init) {
        [self.safeTable bc_showLoading];
    }
    BCUserSafeCenterRequest *request = [BCUserSafeCenterRequest new];
    WEAK_SELF
    [request didRequestCompleted:^{
        if (init) {
            [wself.safeTable bc_hiddenLoading];
        }
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserSafeCenterResponse *resp = result;
        [wself handleSafeData:resp.data];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *errorMsg = error.domain;
            [QMUITips showError:errorMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorMsg]];
        }
    }];
    [request requestServer];
}
- (void)handleSafeData:(BCUserSafeCenterData *)data {
    if (data) {
        //更新用户数据
        [BCUserManager sharedUser].safeCenterData = data;
        //
        self.title = data.flow.title;
        //电话处理
        if (![self.safeSource containsObject:self.phone]) {
            [self.safeSource addObject:self.phone];
        }
        self.phone.title = data.flow.phone;
        self.phone.details = data.data.has_phone?data.data.phone:data.flow.status.off;
        //邮箱处理
        if (![self.safeSource containsObject:self.email]) {
            [self.safeSource addObject:self.email];
        }
        self.email.title = data.flow.email;
        self.email.details = data.data.has_email?data.data.email:data.flow.status.off;
        //支付密码处理
        if (![self.safeSource containsObject:self.payPasswrod]) {
            [self.safeSource addObject:self.payPasswrod];
        }
        self.payPasswrod.title = data.flow.pay_pass;
        self.payPasswrod.details = data.data.has_pay_pass?data.flow.status.on:data.flow.status.not_pay_pass;
        //指纹或面容登录处理
        if ([LocalAuthenticationManager sharedLocalAuth].isSupportLocalAuth) {
            if (![self.safeSource containsObject:self.fingerprintLogin]) {
                [self.safeSource addObject:self.fingerprintLogin];
            }
            DDLABiometryType type = [LocalAuthenticationManager sharedLocalAuth].biometryType;
            if (type==DDLABiometryTypeTouchID) {
                self.fingerprintLogin.title = data.flow.fingerprint;
            }else if (type==DDLABiometryTypeFaceID) {
                self.fingerprintLogin.title = data.flow.face_detect;
            }else {
                self.fingerprintLogin.title = nil;
            }
        }else {
            if ([self.safeSource containsObject:self.fingerprintLogin]) {
                [self.safeSource removeObject:self.fingerprintLogin];
            }
        }
    }
    [self.safeTable reloadData];
}


#pragma mark - 跳转actions
//是否手机验证
- (void)toMobilePhoneVerificationAction {
    
    BCMobileVerificationController *phoneVC = [BCMobileVerificationController new];
    [self.navigationController pushViewController:phoneVC animated:true];
    
}
//是否邮箱验证
- (void)toEmailVerificationAction {
    
    BCEmailVerificationController *email = [BCEmailVerificationController new];
    [self.navigationController pushViewController:email animated:true];
}
//是否设置支付密码
- (void)toWalletPasswordSetAction {
    //需要处理数据
    BCUserSafeCenterData *data = [BCUserManager sharedUser].safeCenterData;
    NSString *account;
    BCaptchaSendType sendType = BCaptchaSendTypePhone;
    if (data.data.has_email) {
        account = data.data.email;
        sendType = BCaptchaSendTypeEmail;
    }else if (data.data.has_phone) {
        account = data.data.phone;
        sendType = BCaptchaSendTypePhone;
    }
    if (!account.length) {
        return;
    }
    BCWalletPassSetController *pass = [BCWalletPassSetController new];
    pass.account = account;
    pass.sendType = sendType;
    [self.navigationController pushViewController:pass animated:true];
}


#pragma mark - 处理指纹或面容登录开关操作
/**
 NO说明要去开启 YES说明要关闭
 */
- (void)handleLocalAuthenticationOn:(BOOL)on {
    WEAK_SELF
    self.switchButton.userInteractionEnabled = false;
    [[LocalAuthenticationManager sharedLocalAuth] startLocalAuthenticationFromController:self.navigationController complete:^(BOOL success, NSError *error) {
        wself.switchButton.userInteractionEnabled = true;
        if (success) {
            //进行相关开启或者关闭操作
            if (on) {//直接请求关闭接口
                [wself requestUserFingerprintDelegateAction];
            }else {
                [wself localAuthenticationSuccessToOn];
            }
        }
    }];
}
/**
 指纹或面容验证成功后去开启和关闭
 */
- (void)localAuthenticationSuccessToOn {
    //开启->需要输入登录密码  弹出操作界面
    WEAK_SELF
    [BCLALoginPasswordController showLoginPasswordComplete:^(BOOL success) {
        if (success) {
            [wself.fingerSwitch setOn:true animated:true];
            if (wself.view) {
                BCUserSafeCenterData *safeData = [BCUserManager sharedUser].safeCenterData;
                NSString *successString = safeData.flow.status.on;
                [QMUITips showSucceed:successString inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:successString]];
            }
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [wself.safeTable reloadData];
        });
    }];
}
- (void)localAuthenticationSuccessToClose {
    //关闭则不需要输入登录密码
    [self handleLocalAuthenticationOn:self.fingerSwitch.on];
}
//请求关闭指纹或者面容登录
- (void)requestUserFingerprintDelegateAction {
    [self.safeTable bc_showLoading];
    BCUserFingerPrintDeleteRequest *request = [BCUserFingerPrintDeleteRequest new];
    request.fingerprint = [[BCUserLoginManager sharedLogin] getCurrentUserLoacalAuthenticationCode:[BCUserManager sharedUser].userLogin.user_id];
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.safeTable bc_hiddenLoading];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserFingerPrintDeleteResponse *resp = result;
        if (resp) {
            [wself.fingerSwitch setOn:false animated:true];
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [wself.safeTable reloadData];
        });
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *errorMsg = error.domain;
            [QMUITips showError:errorMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorMsg]];
        }
    }];
    [request requestServer];
}


#pragma mark - safeCenterdataUpdateNotification:
- (void)safeCenterdataUpdateNotification:(NSNotification *)noti {
    [self requestSafeDataInit:false refresh:true];
}



- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UserSafeCenterUpdateNotification object:nil];
}

@end
